package com.lw.leetcode.other.b;

/**
 * Created with IntelliJ IDEA.
 * 393. UTF-8 编码验证
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/13 20:03
 */
public class ValidUtf8 {

    private int mask1 = 1 << 7;
    private int mask2 = (1 << 7) + (1 << 6);

    public boolean validUtf8(int[] data) {
        int m = data.length;
        int index = 0;
        while (index < m) {
            int num = data[index];
            int n = getBytes(num);
            if (n < 0 || index + n > m) {
                return false;
            }
            for (int i = 1; i < n; i++) {
                if ((data[index + i] & mask2) != mask1) {
                    return false;
                }
            }
            index += n;
        }
        return true;
    }

    public int getBytes(int num) {
        if ((num & mask1) == 0) {
            return 1;
        }
        int n = 0;
        int mask = mask1;
        while ((num & mask) != 0) {
            n++;
            if (n > 4) {
                return -1;
            }
            mask >>= 1;
        }
        return n >= 2 ? n : -1;
    }

}
